/** 
 * project: finance-manage 
 * package: com.example.dataAccess 
 * 数据库连接类
 */

package com.example.dataAccess;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import com.example.util.ReadConfig;
import com.example.util.Debug;

public class Connect {

    /* 定义属性连接对象 */
    private Connection connection = null;

    /* 构造方法中对数据库连接进行连接 */
    public Connect() throws IOException, SQLException {
        /* 读取数据库配置文件 */
        ReadConfig readConfigProperties= new ReadConfig();
        Properties properties = readConfigProperties.getDatabaseConfig();

        /* 获取数据库连接信息 */
        String url = properties.getProperty("URL");
        String username = properties.getProperty("USERNAME");
        String password = properties.getProperty("PASSWORD");

        /* 加载驱动 */
        try {
            Class.forName(properties.getProperty("DRIVER"));
        } catch (ClassNotFoundException e) {
            throw new SQLException("加载驱动失败！");
        }

        /* 连接数据库 */
        connection = DriverManager.getConnection(url, username, password);
        Debug.print(getClass(), ":", "数据库连接成功！");
    }

    /* 获取连接对象 */
    public Connection getConnection() {
        return connection;
    }

    /* 关闭连接 */
    public void close() throws SQLException {
        if (connection!= null) {
            connection.close();
        }
    }
}
